#pragma once

#include "Mathf.h"
#include "Matrixf.h"
#include <string>

class Algorithmf
{
public:
    static double StringToDouble(const std::string &input)
    {
        double ans;
        try
        {
            ans = stod(input);
        }
        catch (const std::exception &)
        {
            return 0;
        }
        return ans;
    }
    static int StringToInt(const std::string &input)
    {
        double ans;
        try
        {
            ans = stoi(input);
        }
        catch (const std::exception &)
        {
            return 0;
        }
        return ans;
    }

public:
    // 最小加权二乘
    static Matrix ReweightedLeastSquares(Matrix matrixA, Matrix matrixB,
                                         Matrixf::DiagonalMatrix weight = Matrixf::DiagonalMatrix())
    {
        int row = matrixA.Row();
        int col = matrixA.Col();

        // 如果对角矩阵weight为空，则将所有权置为1
        if (weight.empty())
        {
            weight.resize(row, 1);
        }

        // A的转置
        Matrix AT = Matrixf::TransposeMatrix(matrixA);

        // x矩阵
        Matrix x = Matrixf::CreateMatrix(col, 1);

        Matrix W = Matrixf::CreateDigonal(weight);

        Matrix WT = Matrixf::TransposeMatrix(W);

        x = ((AT * WT * W * matrixA).Inverse()) * (AT * WT * W * matrixB);

        return x;
    }

private:
    Algorithmf() = delete;
};